package uit.nfcmenu.manager;

import java.util.ArrayList;
import java.util.Hashtable;

import uit.nfcmenu.db.adapter.MenuAdapter;
import uit.nfcmenu.db.model.ItemModel;
import uit.nfcmenu.db.model.MenuModel;
import uit.nfcmenu.util.CommConstant;
import uit.nfcmenu.webservice.MyException;
import uit.nfcmenu.webservice.WSMapping;
import android.content.Context;


public class MenuManager {
	private static MenuManager instance;
	private Context mContext;
	protected MenuAdapter mMenuAdapter;

	public MenuManager(Context context) {
		mContext = context;
		mMenuAdapter = new MenuAdapter(mContext);
	}

	public static MenuManager getInstance(Context context) {
		if (instance == null) {
			instance = new MenuManager(context);
		}
		return instance;
	}

	public void updateMenuToDB(ArrayList<MenuModel> arrayMenuList) {
		for (MenuModel menu : arrayMenuList) {
			mMenuAdapter.updateMenuModel(menu);
		}
	}

	public ArrayList<MenuModel> getAllMenuInDB() {
		return mMenuAdapter.selectAll();
	}

	public void initMenu() {
		ArrayList<ItemModel> dbItems = ItemManager.getInstance(mContext)
				.getAllItemsInDB();

		// create hashTable for all (itemId, menuId)
		CommConstant.itemsMenus = new Hashtable<Integer, Integer>();
		for (int i = 0; i < dbItems.size(); i++) {
			CommConstant.itemsMenus.put(dbItems.get(i).getId(), 
					dbItems.get(i).getMenuId());
		}

		// create hashTable for all (menuId, )
		ArrayList<MenuModel> arrayMenu = getAllMenuInDB();
		CommConstant.menuImgLinks = new Hashtable<Integer, String>();
		for (int i = 0; i < arrayMenu.size(); i++) {
			int id = arrayMenu.get(i).getId();
			String link = arrayMenu.get(i).getImageLink();
			CommConstant.menuImgLinks.put(id, link);
		}
	}

	public void insertMenuToDB(ArrayList<MenuModel> arrayMenuList) {
		for (MenuModel menu : arrayMenuList) {
			mMenuAdapter.insertMenuModel(menu);
		}
	}

	public ArrayList<MenuModel> selectMenus() {
		return mMenuAdapter.selectAll();
	}

	/*
	 *  Note:
	 *   This method sync all menu from server to db
	 */
	public void updateMenus() throws MyException {
		// get data from server
		ArrayList<MenuModel> models = null;
		models = WSMapping.getAllMenusFromServer(mContext);
		
		// update data to db
		MenuAdapter adapter = new MenuAdapter(mContext);
//		MenuModel model;
		if (models != null && models.size() > 0) {
			// TODO build #1 => build #2
			// solution build #1
//			for (int i = 0; i < models.size(); i++) {
//				model = adapter.loadMenuModel(models.get(i).getId());
//				if (model == null) {
//					adapter.insertMenuModel(models.get(i));
//				} else {
//					adapter.updateMenuModel(models.get(i));
//				}
//			}
			// solution build #2
			// drop db and update all new date into db
			adapter.deleteDatabase();
			adapter.insertMenuModels(models);
		}
	}
}
